<!DOCTYPE html>
<html>
<head>
    <!--Import Google Icon Font-->
    <link type="text/css" rel="stylesheet" href="css/material-icons.css"/>
    <!--Import materialize.css-->
    <link type="text/css" rel="stylesheet" href="css/materialize.min.css" media="screen,projection"/>
    <title>Control Instance</title>

    <!--Let browser know website is optimized for mobile-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

</head>

<body>
<nav class="blue-grey ">
    <div class="container">
        <div class="nav-wrapper">
            <a href="#" class="brand-logo" id="instance_name">Instance Name</a>
            <ul id="nav-mobile" class="right">
              <li><a href="#" id="keyboard_btn"><i class="material-icons">keyboard_hide</i></a></li>
              <!-- <li><a href="#" id="copy_btn"><i class="material-icons">content_copy</i></a></li> -->
              <li><a href="#" id="insert_btn"><i class="material-icons">arrow_drop_down</i></a></li>
              <li><a href="#" id="eject_btn"><i class="material-icons">eject</i></a></li>
              <li><a href="#" id="shutdown_btn"><i class="material-icons">power_settings_new</i></a></li>
              <li><a href="#" id="reboot_btn"><i class="material-icons">rotate_right</i></a></li>
              <li><a href="#" id="reset_btn"><i class="material-icons">refresh</i></a></li>
                <!-- <li><a href="#"><i class="material-icons right dropdown-trigger" data-target="operators_menu">list</i></a></li> -->
            </ul>
        </div>
    </div>
</nav>

<div class="container">
  <div class="section">
    <div class="row">
      <div class="col m12" id="novnc">
      </div>
    </div>
  </div>
  <div class="modal" id="insert_modal">
      <!--hide model -->
      <div class="modal-content">
          <h4>Insert media into instance</h4>
          <div class="row">
            <div class="input-field col m4">
                <select name="media" id="insert_options">
                </select>
                <label>Choose Media</label>
            </div>
          </div>
      </div>
      <div class="modal-footer">
          <a href="#" class="modal-close waves-effect waves-green btn-flat">No</a>
          <a href="#" class="modal-close waves-effect waves-green btn-flat" id="insert_confirm_link">Yes</a>
      </div>
  </div>
  <div class="modal" id="eject_modal">
      <!--hide model -->
      <div class="modal-content">
          <h4>Eject media from instance</h4>
          <p id="eject_confirm_content"></p>
      </div>
      <div class="modal-footer">
          <a href="#" class="modal-close waves-effect waves-green btn-flat">No</a>
          <a href="#" class="modal-close waves-effect waves-green btn-flat" id="eject_confirm_link">Yes</a>
      </div>
  </div>
</div>

<script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="js/materialize.min.js"></script>
<script type="text/javascript" src="js/nano.js"></script>
<script type="module">
  import RFB from './js/novnc/core/rfb.js';

  function parseQueryString(){
    var url = window.location.search;
    var queryParams = new Map();
    var queryString = url.substring( url.indexOf('?') + 1 );
    if (0 === queryString.length){
      return queryParams;
    }
    var values = queryString.split("&");
    values.forEach((value) => {
      var p = value.split('=');
      queryParams.set(p[0], p[1]);
    });
    return queryParams;
  }

  function openChannel(id){
    $.post(
      '/monitor_channels/',
      JSON.stringify({
          "guest": id
      }),
      function(result){
        if (0 != result['error_code']) {
            M.toast({html: 'create channel fail:' + result['message']});
            return;
        }
        var channel = result['data']['id'];
        var secret = result['data']['password'];
        establishChannel(channel, secret);
      },
      "json"
    );
  }

  var rfb;
  function establishChannel(channel, password){
    var options = new Object();
    options.credentials = {"password": password};
    var url = "ws://" + window.location.hostname;
    if (window.location.port){
      url += ":" + window.location.port;
    }
    url += "/monitor_channels/" + channel;

    var canvas = document.getElementById('novnc');
    rfb = new RFB(canvas, url, options);
  }

  $(function(){
    var params = parseQueryString();
    if (!params.has('instance')){
      M.toast({html: 'must specify instance'});
      return;
    }
    var instanceID = params.get('instance');
    openChannel(instanceID);

    $('#keyboard_btn').bind("click", function(){
      rfb.sendCtrlAltDel();
    });

  });
</script>

<script>
  function parseQueryString(){
    var url = window.location.search;
    var queryParams = new Map();
    var queryString = url.substring( url.indexOf('?') + 1 );
    if (0 === queryString.length){
      return queryParams;
    }
    var values = queryString.split("&");
    values.forEach((value) => {
      var p = value.split('=');
      queryParams.set(p[0], p[1]);
    });
    return queryParams;
  }

  function updateInstanceInfo(id){
    $.getJSON(
      "/guests/" + id,
      function(result){
        if (0 != result['error_code']) {
            M.toast({html: 'get instance info fail:' + result['message']});
            return;
        }
        var instanceName = result['data']['name'];
        var instanceID = result['data']['id'];
        $('#instance_name').text(instanceName);
        $('#shutdown_btn').bind("click", function(){
          N.StopInstance(instanceName, instanceID);
        });
        $('#reboot_btn').bind("click", function(){
          N.RestartInstance(instanceName, instanceID);
        });
        $('#reset_btn').bind("click", function(){
          N.ResetInstance(instanceName, instanceID);
        });
        // $('#insert_btn').attr('onclick', 'selectInsertMedia("'+ instanceName +'","' + instanceID + '")');
        // $('#eject_btn').attr('onclick', 'confirmEject("'+ instanceName +'", "' + instanceID + '")');
        $('#insert_btn').bind("click", function(){
          selectInsertMedia(instanceName, instanceID);
        });
        $('#eject_btn').bind("click", function(){
          confirmEject(instanceName, instanceID);
        });
      }
    );
  }

  //insert media
  function selectInsertMedia(name, id){
    $('#insert_confirm_link').attr('onclick', 'insertMedia("' + name + '", "' + id +'")');
    var queryURL = '/media_image_search/?session=' + N.GetSessionID();
    $.getJSON(
      queryURL,
      function(result){
        if (0 != result['error_code']) {
            M.toast({html: 'fetch media fail: ' + result['message'], outDuration: 600});
            return;
        }
        if (!result['data']){
          M.toast({html: 'no media image available', outDuration: 600});
          return;
        }
        $('#insert_options').empty();
        result['data'].forEach((media)=>{
          $('#insert_options').append(
            $('<option>').attr('value', media['id']).text(media['name'])
          );
        });
        M.FormSelect.init($('#insert_options'));
        var instance = M.Modal.getInstance($('#insert_modal'));
        instance.open();
      }
    )
  }

  function insertMedia(name, id){
    var media = $('#insert_options').val();
    var mediaName = $('#insert_options :selected').text();
    $.post(
      '/instances/' + id + '/media',
      JSON.stringify({
        "source": media
      }),
      function(result){
        if (0 != result['error_code']) {
            M.toast({html: 'insert media fail: ' + result['message'], outDuration: 1000});
            return;
        }
        M.toast({html: 'media "' + mediaName + '" insert into ' + name });
      },
      "json"
    );
  }

  //eject media
  function confirmEject(name, id){
    $('#eject_confirm_content').text('Are you sure to eject media of guest ' + name);
    $('#eject_confirm_link').attr('onclick', 'ejectMedia("' + name + '", "' + id +'")');
    var instance = M.Modal.getInstance($('#eject_modal'));
    instance.open();
  }

  function ejectMedia(name, id) {
    $.ajax({
     url:'/instances/' + id + '/media',
     type: "DELETE",
     dataType: "json",
     data:JSON.stringify({
     }),
     success: function (result) {
         if (0 != result['error_code']) {
             M.toast({html: 'eject media fail: ' + result['message'], outDuration: 1000});
             return;
         }
         M.toast({html: 'media of guest "' + name + '" ejected'})
     }
    });
  }

  $(function(){
    M.AutoInit();
    M.Modal.init($('.modal'));
    var params = parseQueryString();
    if (!params.has('instance')){
      M.toast({html: 'must specify instance'});
      return;
    }
    var instanceID = params.get('instance');
    updateInstanceInfo(instanceID);
  });
</script>
</body>
</html>
